/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package io.iec.edp.caf.multicontext.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.loader.LaunchedURLClassLoader;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 子模块管理器
 *
 * @author guowenchang
 */
@Slf4j
public class ModuleManager implements Iterable<Module> {

    private final Map<String, Module> moduleMap = new HashMap<>();

    public void addModule(Module module) {
        moduleMap.put(module.getName(), module);
    }

    private final Map<String, Class> classCache = new ConcurrentHashMap<>();

    private LaunchedURLClassLoader internalClassloader;

    public void setInternalClassloader(LaunchedURLClassLoader internalClassloader) {
        this.internalClassloader = internalClassloader;
    }

    @Override
    public Iterator<Module> iterator() {
        return moduleMap.values().iterator();
    }

    public int size() {
        return moduleMap.size();
    }

    public Set<Class<?>> getClassesWithAnnotation(Class<? extends Annotation> annotation) {
        Set<Class<?>> result = new HashSet<>();
        Field field;
        try {
            field = ClassLoader.class.getDeclaredField("classes");
            field.setAccessible(true);
            Vector<Class> vector = (Vector<Class>) ((Vector<Class>) field.get(internalClassloader)).clone();
            for (Class c : vector) {
                try {
                    if (c.getAnnotation(annotation) != null) {
                        result.add(c);
                        classCache.put(c.getName(), c);
                    }
                } catch (Throwable e) {
                    log.info("getClassesWithAnnotation异常："+"当前Annotation:"+annotation.getClass().getName(),e);
//                    System.out.println(c.getName());
                }
            }
        } catch (Throwable e) {
            log.info("getClassesWithAnnotation异常："+"当前Annotation:"+annotation.getClass().getName(),e);
        }

        return result;
    }

    public Class getClassByName(String name) throws ClassNotFoundException {
        Class c = classCache.get(name);
        if (c == null) {
            c = getClassFromClassloader(name);
            if (c == null) {
                throw new ClassNotFoundException(name);
            }
        }

        classCache.put(name, c);
        return c;
    }

    private Class getClassFromClassloader(String name) {
        try {
            Class c = internalClassloader.loadClass(name);
            return c;
        } catch (ClassNotFoundException e) {
            return null;
        }
    }

    /**
     * 获取指定的模块，是区分大小写的
     * @param moduleName
     * @return
     */
    public Module getModule(String moduleName){
        Module m = null;
        m = moduleMap.get(moduleName);
        return m;
    }
}
